#!/usr/bin/perl
# A very simple script that generates a page
# based on a GREP through the temp/persons.tab file
use LinuxCounter;
use CounterCGI;
use CGI::Carp;

$] > 5.008 && binmode(STDOUT, ":utf8"); # set web page output to utf-8
#chdir("/home/counter");
LinuxCounter::cgi();

# Get the input
if ($ENV{"QUERY_STRING"}) {
    $buffer = $ENV{"QUERY_STRING"};
    warn "Query mode - read $buffer\n";
} else {
    read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}
#open(DEBUGLOG, ">>$logprefix/debuglog");
#open(EVENTLOG, ">>$logprefix/eventlog");
#$date = scalar(localtime);
#print EVENTLOG scalar(localtime), " person-counter.pl\n";
#print DEBUGLOG "$0 got $buffer\n";
# Split the name-value pairs
@pairs = split(/&/, $buffer);

foreach $pair (@pairs)
{
    ($name, $value) = split(/=/, $pair);
    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

    # Uncomment for debugging purposes
    warn "Setting $name to $value<P>";
    #if ($value =~ /[\000-\037]/) {
    #	&errorForm("bogon value");
    #}
    $entry{$name} = $value;

}
if ($entry{search} && $entry{search} =~ /^[\\|\. a-z0-9A-Z_@-]+$/) {
    $flags = "";
    if ($entry{case} eq "ignore") {
       $flags .= "-i ";
    } 
    $entry{search} =~ s/\|/\t/g; # record boundary
    $| = 1; # flush stdout
    warn "grep $flags $entry{search} temp/persons.tab\n";
    print "Content-type: text/html; charset=\"utf-8\"\n\n";
    system("grep $flags \"$entry{search}\" temp/persons.tab | writers/checkoutpage");
} else {
    print <<EoF;
Content-type: text/html; charset="utf-8"

<html>
EoF

CounterCGI::pagehead("Search error");
print "<body bgcolor=\"white\">\n";
CounterCGI::pagetop($entry);

print <<EoF;
<h1><img src="/gifs/Logo-small.png" alt="Linux Counter Logo">
Search Error</h1>
Can't search for search=$entry{search}
<hr>
Contact: <a href="mailto:webmaster&#x40;counter.li.org">Webmaster&#x40;counter.li.org</a>
</body>
</html>
EoF
}

